<template>
  <div>
    <div class="top-fixed">
      <new-search-bar bgSearch="c-bg-white c-pt24-i" :searchText="searchName" @search="startSearch" @cancel="startSearch"></new-search-bar>
      <my-small-tabbar id="tab-bar" :tabList="tabList" :tabIndex="clockInType" @changeTab="changeType"></my-small-tabbar>
    </div>
    <div class="c-hh170"></div>
    <div class="c-ph24">
      <div @click="clickGoClockInDetail(item)" class="c-flex-row c-pv24 c-bd-b1" v-for="(item,index) in clockInList" :key="index">
        <div class="c-ww180 c-hh120 c-br16 c-text-hidden">
          <CoverImg coverSizeClass="c-w100 c-h c-text-hidden c-br16" imgClass="c-br16" :coverUrl="$addXossFilter(item.cover, require('@/assets/defult270.png'))" />
        </div>
        <div class="c-flex-column c-pl20 c-flex-grow1 c-w0 c-pv4 c-justify-sb">
          <div class="c-fs24 c-text-ellipsis2"><span v-if="item.payType == 4">【奖金{{item.type == 3 ? "返还" : "平分"}}】</span>{{item.name}}</div>
          <div class="c-flex-row c-justify-sb c-aligni-center">
            <span class="c-fc-xmlred c-fw600 c-lh" :class="(item.payType == 2 || item.payType == 4) && Number(item.price) != 0 ? 'c-fs26' : 'c-fs22'">
              <span class="c-fs20" v-if="(item.payType == 2 || item.payType == 4) && Number(item.price) != 0">{{'￥' | iosPriceFilter}}</span>{{item.payType | priceValueFilter(item.price, ckFrom.clockIn, item.optimal, 'index')}}
            </span>
            <div v-if="enableShowModuleView == 1 || !(enableHiddenModules && enableHiddenModules.includes(ckFrom.clockIn))" class="c-fs18 c-fc-gray">{{item.hasMan}}人参与</div>
          </div>
        </div>
      </div>
      <loading-status-tem :showLoading="dataStatus == 'LOADING'" :noMoreData="dataStatus == 'NO_MORE_DATA'" :noData="dataStatus == 'NO_DATA'" noDataText="暂无打卡"></loading-status-tem>
    </div>
    <nav-bottom-bar :itemIndex="6" v-if="showNavBottomBar"></nav-bottom-bar>
  </div>
</template>

<script>
import newSearchBar from "@/components/templates/common/newSearchBar.vue"
import loadingStatusTem from "@/components/templates/common/loadingStatusTem.vue";
import NavBottomBar from "@/components/templates/common/navBottomBar.vue";
import MySmallTabbar from "@/components/templates/common/MySmallTabbar.vue";
import CoverImg from '@/components/templates/common/coverImg.vue';
import { utilJs } from "@/utils/common.js";
let pageIndex = 1;
let LIMIT = 10;
export default {
  name: "ClockInList",
  components: {
    loadingStatusTem,
    NavBottomBar,
    MySmallTabbar,
    newSearchBar,
    CoverImg
  },
  props: [],
  data() {
    return {
      theme: localStorage.getItem("colorName") ? localStorage.getItem("colorName") : "mb5_default",
      themeName: localStorage.getItem('themeName') ? localStorage.getItem('themeName') : 'mb5',
      searchName: '',
      dataStatus: 'HAS_MORE_DATA',
      clockInList: [],
      showNavBottomBar: false,
      tabList: [],
      clockInType: 1,
      ckFrom: global.ckFrom,
      enableShowModuleView: localStorage.getItem("cfg") ? JSON.parse(localStorage.getItem("cfg")).enableShowModuleView : 1,
      enableHiddenModules: localStorage.getItem("cfg") ? JSON.parse(localStorage.getItem("cfg")).enableHiddenModules : [],
    };
  },
  created() {
    utilJs.appShare(this);
  },
  mounted() { },
  methods: {
    //更换类别
    changeType(tabIndex) {
      if (this.clockInType != tabIndex) {
        pageIndex = 1;
        this.clockInList = [];
        this.clockInType = tabIndex;
        this.getClockInList();
      }
    },
    iosAppRouteChange(toPath) {
      if (utilJs.isIOSApp()) {
        window.webkit.messageHandlers.iosWechatRoute.postMessage(toPath);
      } else if (utilJs.isAndoridNewApp()) {
        let data = {
          path: toPath
        }
        window.androidWechatRoute.doAction(JSON.stringify(data))
      } else {
        this.$routerGo(this, "push", { path: toPath });
      }
    },
    startSearch(e) {
      this.searchName = e.searchValue;
      pageIndex = 1;
      this.clockInList = []
      utilJs.toPageScrollTop();
      this.getClockInList();
    },
    clickGoClockInDetail(itemInfo) {
      if (itemInfo.isJoin != 1) {
        let toPath = `/homePage/clockIn/clockInDetail?clockInId=${itemInfo.signColId}`;
        this.iosAppRouteChange(toPath);
      } else {
        this.enterClock(itemInfo);
      }
    },
    enterClock(clockInInfo) {
      let title = clockInInfo.name;
      let shareImg = clockInInfo.cover;
      let shareUrl = `${window.location.href.split("#")[0]}#/homePage/clockIn/clockInDetail?clockInId=${clockInInfo.signColId}&refereeId=${localStorage.getItem("userId")}`;
      let shareDesc = clockInInfo.shareDesc || "点击查看详情";
      let shareData = {
        title: title,
        shareImg: shareImg,
        shareUrl: shareUrl,
        shareDesc: shareDesc
      };
      localStorage.setItem("homeWorkShareInfo", JSON.stringify(shareData));
      switch (clockInInfo.type) {
        case 1:
          //日历打卡,若当前日期不在开始日期和结束日期之间，则从开始日期进入，否则从当前日期进入
          let startTimeTamp = new Date(clockInInfo.startTime.replace(/-/g, "/")).getTime();
          let endTimeTamp = new Date(clockInInfo.endTime.replace(/-/g, "/")).getTime();
          let nowTimeTamp = new Date().getTime();
          let curTime = utilJs.dateFormat(nowTimeTamp);
          if (nowTimeTamp < startTimeTamp || nowTimeTamp > endTimeTamp) {
            curTime = clockInInfo.startTime;
          }
          this.iosAppRouteChange(`/homePage/clockIn/stuHomeWork?workType=1&clockInId=${clockInInfo.signColId}&curDate=${curTime}`);
          break;
        case 2:
          //作业打卡，如果超过一个作业，则进入作业列表，否则进入作业详情
          let nextUrl = `/homePage/clockIn/stuHomeWork?workType=2&clockInId=${clockInInfo.signColId}&curId=${clockInInfo.hwId}`;
          this.iosAppRouteChange(nextUrl);
          break;
        case 3:
          //闯关打卡
          this.iosAppRouteChange(`/homePage/clockIn/stuHomeWork?workType=3&clockInId=${clockInInfo.signColId}&curId=${clockInInfo.hwId}`);
          break;
      }
    },
    // 获取是否有打卡数据
    getClockDate() {
      utilJs.getMethod(
        `${global.apiurl}signCard/getSignCardNumber`,
        res => {
        //  "calendarSign":1,//日历打卡 1有 0没有
        //  "homeworkSign":1,//作业打卡
        //  "rushSign":1,//闯关打卡
          if (res.calendarSign) {
            this.tabList.push({
              title: '日历打卡',
              index: 1,
            })
            this.clockInType = 1
          }
          if (res.homeworkSign) {
            this.tabList.push({
              title: '作业打卡',
              index: 2,
            })
            if (!res.calendarSign) {
              this.clockInType = 2
            }
          }
          if (res.rushSign) {
            this.tabList.push({
              title: '闯关打卡',
              index: 3,
            })
            if (!res.calendarSign && !res.homeworkSign) {
              this.clockInType = 3
            }
          }
          this.getClockInList()
        },
        failRes => {

        }
      );
    },
    getClockInList() {
      if (this.dataStatus == 'LOADING') {
        return;
      }
      this.dataStatus = 'LOADING';
      utilJs.getMethod(
        `${global.apiurl}signCard/type/${this.clockInType}?page=${pageIndex}&limit=${LIMIT}&searchName=${this.searchName}`,
        res => {
          if (pageIndex == 1) {
            this.clockInList = res.data;
          } else {
            this.clockInList = [...this.clockInList, ...res.data];
          }
          if (res.data && (res.data.length < LIMIT)) {
            this.dataStatus = pageIndex == 1 && res.data.length == 0 ? 'NO_DATA' : 'NO_MORE_DATA';
          } else {
            this.dataStatus = 'HAS_MORE_DATA';
            pageIndex++;
          }
        },
        failRes => {
          this.dataStatus = 'DATA_ERROR';
        }
      );
    },
    //分享
    wechatShare: function () {
      let title = '打卡专区';
      let shareUrl = `${window.location.href.split("#")[0]}#${this.$route.path}?refereeId=${localStorage.getItem("userId")}`;
      let shareDesc = "点击查看详情";
      utilJs.wechatConfig(shareUrl, title, "", shareDesc);
    },
    //手机端分享
    appShare: function () {
      let title = '打卡专区';
      let shareUrl = `${window.location.href.split("#")[0]}#${this.$route.path}?refereeId=${localStorage.getItem("userId")}`;
      let shareDesc = "点击查看详情";
      utilJs.appShareTrue(title, "", shareUrl, shareDesc);
    },
    windowScrollFunction() {
      utilJs.handleLoading(() => {
        if (this.dataStatus == 'HAS_MORE_DATA' && this.clockInList.length > 0) {
          this.getClockInList();
        }
      });
    },
    initData() {
      pageIndex = 1;
      this.searchName = '';
      this.dataStatus = 'HAS_MORE_DATA';
      this.clockInList = [];
      this.tabList = []
      this.getClockDate()
      // this.getClockInList();
      let companyAuth = localStorage.getItem("companyAuth") && JSON.parse(localStorage.getItem("companyAuth"));
      if (companyAuth.companyNav && companyAuth.companyNav.length > 0) {
        let arrClockFilter = companyAuth.companyNav.filter((item) => {
          return item.navType == 6;
        });
        this.showNavBottomBar = arrClockFilter.length > 0;
      }
    },
  },
  activated() {
    setDocumentTitle("打卡专区");// eslint-disable-line
    if (utilJs.checkNeedInitData(this.clockInList)) {
      this.initData()
    }
    // this.initData();
    this.wechatShare();
    window.addEventListener('scroll', this.windowScrollFunction);
  },
  deactivated() {
    // this.dataStatus = 'NO_MORE_DATA';
    window.removeEventListener('scroll', this.windowScrollFunction);
  }
};
</script>

<style scoped>
  #tab-bar {
    padding-bottom: .5rem;
  }
  .top-fixed {
    position: fixed;
    z-index: 10;
    width: 100%;
    background: #fff;
    max-width: 640px;
  }
</style>